<template>
	<view class="page-container">
		<!-- 头部操作区 -->
		<uni-section class="mb-10 page-title" title="下单列表管理" type="line">
			<template v-slot:right>
				<view class="opts">
					<button size="mini" class="btn btn-primary" @click="handleImport" :disabled="loading">
						<uni-icons v-if="loading" type="spinner-cycle" size="14" color="#fff" />
						{{ loading ? '处理中...' : '导入' }}
					</button>
					<button size="mini" class="btn btn-danger" @click="handleClear" :disabled="loading">
						清空
					</button>
					<button v-if="selectedItems.size > 0" size="mini" class="btn btn-danger" @click="handleBatchDelete"
						:disabled="loading">
						批量删除({{ selectedItems.size }})
					</button>
				</view>
			</template>
		</uni-section>

		<!-- 订单列表 -->
		<uni-row class="row-box">
			<uni-col class="col-item" :span="24" v-for="(item, index) in list" :key="item._id || index">
				<view class="item-card" :class="{ 'editing': editingIndex === index }">
					<view class="item-content">
						<!-- 图片上传区域 -->
						<view class="image-container" @click="handleUpload(index)">
							<image :src="item.img || '/static/default-image.png'" mode="aspectFill"
								class="item-image" />
							<view v-if="!item.img" class="upload-overlay">
								<uni-icons type="plusempty" size="24" color="#999" />
								<text class="upload-text">添加图片</text>
							</view>
						</view>

						<!-- 内容区域 - 统一高度 -->
						<view class="content-container">
							<!-- 编辑状态 -->
							<template v-if="editingIndex === index">
								<view class="edit-fields">
									<view class="input-field">
										<text class="input-label">序号</text>
										<input type="text" class="edit-input" v-model="editForm.serial"
											placeholder="请输入序号" />
									</view>
									<view class="input-field">
										<text class="input-label">名称</text>
										<input type="text" class="edit-input" v-model="editForm.title"
											placeholder="请输入名称" />
									</view>
									<view class="input-field">
										<text class="input-label">描述</text>
										<input type="text" class="edit-input" v-model="editForm.desc"
											placeholder="请输入描述" />
									</view>
								</view>
							</template>

							<!-- 展示状态 -->
							<template v-else>
								<view class="display-fields">
									<view class="info-row">
										<text class="info-label">序号：</text>
										<text class="info-value">{{ item.serial }}</text>
									</view>
									<view class="info-row">
										<text class="info-label">名称：</text>
										<text class="info-value">{{ item.title }}</text>
									</view>
									<view class="info-row">
										<text class="info-label">描述：</text>
										<text class="info-value">{{ item.desc }}</text>
									</view>
								</view>
							</template>
						</view>

						<!-- 操作按钮 -->
						<view class="action-buttons">
							<checkbox :value="item._id" :checked="selectedItems.has(item._id)"
								@click="toggleSelect(item._id)" v-if="!editingIndex === index"
								class="selection-checkbox" />

							<template v-if="editingIndex === index">
								<button class="action-btn save-btn" size="mini" @click="saveEdit(index)"
									:disabled="saving">
									<uni-icons v-if="saving" type="spinner-cycle" size="14" color="#fff" />
									{{ saving ? '保存中...' : '保存' }}
								</button>
								<button class="action-btn cancel-btn" size="mini" @click="cancelEdit"
									:disabled="saving">
									取消
								</button>
							</template>

							<template v-else>
								<button class="action-btn edit-btn" size="mini" @click="startEdit(index, item)"
									:disabled="loading">
									编辑
								</button>
								<button class="action-btn delete-btn" size="mini"
									@click="confirmDelete(index, item._id)" :disabled="loading">
									删除
								</button>
							</template>
						</view>
					</view>
				</view>
			</uni-col>

			<!-- 新增按钮 -->
			<view class="add-actions">
				<button class="btn add-btn" hover-class="is-hover" size="mini" @click="handleAdd"
					:disabled="loading || editingIndex !== null">
					<uni-icons type="plus" size="14" color="#fff" />
					新增
				</button>
			</view>
		</uni-row>

		<!-- 加载指示器 -->
		<uni-load-more v-if="loading" status="loading" />

		<!-- 删除确认对话框 -->
		<uni-popup ref="deleteDialog" type="dialog">
			<uni-popup-dialog type="warn" title="确认删除" content="确定要删除这条数据吗？" :duration="2000" :before-close="true"
				@confirm="executeDelete" @close="cancelDelete" />
		</uni-popup>
		<ver />
	</view>
</template>

<script setup>
	import ver from '@/components/ver.vue'
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		getOrder,
		addOrder,
		updateOrder,
		deleteOrder,
		importOrders,
		clearOrders,
		batchDeleteOrders
	} from '@/api/order.js';

	// 响应式数据
	const list = ref([]);
	const loading = ref(false);
	const saving = ref(false);
	const selectedItems = ref(new Set());
	const editingIndex = ref(null);
	const deleteIndex = ref(null);
	const deleteId = ref(null);
	const editForm = ref({
		serial: '',
		title: '',
		desc: '',
		img: ''
	});
	const deleteDialog = ref(null);

	// 初始化加载数据
	const loadData = async () => {
		try {
			loading.value = true;
			const res = await getOrder();
			list.value = res.map(item => ({
				...item,
				img: item.img || '',
				title: item.title || '未命名',
				serial: item.serial || '无序号',
				desc: item.desc || '无描述',
				_id: item._id || null
			}));
		} catch (error) {
			uni.showToast({
				title: error.message || '加载失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};

	// 开始编辑
	const startEdit = (index, item) => {
		editingIndex.value = index;
		editForm.value = {
			serial: item.serial,
			title: item.title,
			desc: item.desc,
			img: item.img
		};
	};

	// 取消编辑
	const cancelEdit = () => {
		editingIndex.value = null;
		editForm.value = {
			serial: '',
			title: '',
			desc: '',
			img: ''
		};
	};

	// 保存编辑
	const saveEdit = async (index) => {
		try {
			saving.value = true;
			const item = list.value[index];
			const formData = editForm.value;

			// 验证表单
			if (!formData.serial.trim()) {
				throw new Error('序号不能为空');
			}
			if (!formData.title.trim()) {
				throw new Error('名称不能为空');
			}

			if (item._id) {
				// 更新已有项
				const {
					updated
				} = await updateOrder(item._id, formData);
				if (updated) {
					Object.assign(item, formData);
					uni.showToast({
						title: '更新成功',
						icon: 'success'
					});
				}
			} else {
				// 新增项
				const {
					id
				} = await addOrder(formData);
				item._id = id;
				Object.assign(item, formData);
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
			}

			editingIndex.value = null;
		} catch (error) {
			uni.showToast({
				title: error.message || '操作失败',
				icon: 'none'
			});
		} finally {
			saving.value = false;
		}
	};

	// 确认删除
	const confirmDelete = (index, id) => {
		deleteIndex.value = index;
		deleteId.value = id;
		deleteDialog.value.open();
	};

	// 执行删除
	const executeDelete = async () => {
		try {
			loading.value = true;
			if (deleteId.value) {
				await deleteOrder(deleteId.value);
			}
			list.value.splice(deleteIndex.value, 1);
			selectedItems.value.delete(deleteId.value);
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			});
		} catch (error) {
			uni.showToast({
				title: error.message || '删除失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
			deleteIndex.value = null;
			deleteId.value = null;
		}
	};

	// 取消删除
	const cancelDelete = () => {
		deleteIndex.value = null;
		deleteId.value = null;
	};

	// 图片上传
	const handleUpload = async (index) => {
		try {
			uni.chooseImage({
				count: 1,
				success: async (res) => {
					const tempFilePath = res.tempFilePaths[0];
					uni.showLoading({
						title: '上传中...'
					});

					const uploadRes = await uniCloud.uploadFile({
						filePath: tempFilePath,
						cloudPath: `order-images/${Date.now()}.jpg`
					});

					if (editingIndex.value === index) {
						editForm.value.img = uploadRes.fileID;
					} else {
						list.value[index].img = uploadRes.fileID;
					}

					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
				},
				fail: (err) => {
					console.error('选择图片失败', err);
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					});
				}
			});
		} catch (error) {
			uni.showToast({
				title: '上传失败',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};

	// 新增条目
	const handleAdd = () => {
		list.value.push({
			img: '',
			title: '新名称',
			serial: '新序号',
			desc: '新描述',
			_id: null
		});
		startEdit(list.value.length - 1, list.value[list.value.length - 1]);
	};

	// 导入数据
	const handleImport = async () => {
		loading.value = true;

		try {
			// 1. 选择文件（使用更可靠的实现方式）
			const res = await new Promise((resolve, reject) => {
				let hasResponded = false;

				const timer = setTimeout(() => {
					if (!hasResponded) {
						hasResponded = true;
						reject(new Error('选择文件超时'));
					}
				}, 30000); // 30秒超时

				uni.chooseFile({
					count: 1,
					type: 'file',
					extension: ['.csv'],
					success: (res) => {
						if (!hasResponded) {
							clearTimeout(timer);
							hasResponded = true;

							// 关键改进：检查是否真的选择了文件
							if (!res.tempFiles || res.tempFiles.length === 0) {
								reject(new Error('未选择文件'));
							} else {
								resolve(res);
							}
						}
					},
					fail: (err) => {
						if (!hasResponded) {
							clearTimeout(timer);
							hasResponded = true;
							reject(new Error(`选择文件失败: ${err.errMsg}`));
						}
					},
					complete: () => {
						// 确保无论如何都能清除loading
						if (!hasResponded) {
							clearTimeout(timer);
							loading.value = false;
						}
					}
				});
			});

			// 2. 处理文件内容（只有真正选择了文件才会执行到这里）
			const file = res.tempFiles[0];
			const fileContent = await readFile(file);
			const parsedData = parseCSV(fileContent);
			const {
				imported
			} = await importOrders(parsedData);

			if (imported) {
				await loadData();
				uni.showToast({
					title: '导入成功',
					icon: 'success'
				});
			}
		} catch (error) {
			console.error('导入错误:', error);
			// 不显示技术性错误给用户
			const userMessage = error.message.includes('未选择') ? error.message : '导入失败';
			uni.showToast({
				title: userMessage,
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};

	// 清空数据
	const handleClear = async () => {
		try {
			loading.value = true;
			const {
				deleted
			} = await clearOrders();
			if (deleted) {
				list.value = [];
				selectedItems.value.clear();
				uni.showToast({
					title: '已清空',
					icon: 'success'
				});
			}
		} catch (error) {
			uni.showToast({
				title: error.message || '清空失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};

	// 批量删除
	const handleBatchDelete = async () => {
		try {
			loading.value = true;
			const ids = Array.from(selectedItems.value);
			const {
				deleted
			} = await batchDeleteOrders(ids);
			if (deleted) {
				list.value = list.value.filter(item => !selectedItems.value.has(item._id));
				selectedItems.value.clear();
				uni.showToast({
					title: '批量删除成功',
					icon: 'success'
				});
			}
		} catch (error) {
			uni.showToast({
				title: error.message || '批量删除失败',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	};

	// 切换选择状态
	const toggleSelect = (id) => {
		if (selectedItems.value.has(id)) {
			selectedItems.value.delete(id);
		} else {
			selectedItems.value.add(id);
		}
	};

	const readFile = (file) => {
		return new Promise((resolve, reject) => {
			// #ifdef H5
			// H5 environment
			const reader = new FileReader();
			reader.onload = (e) => resolve(e.target.result);
			reader.onerror = (e) => reject(new Error('文件读取失败'));
			reader.readAsText(file);
			// #endif

			// #ifndef H5
			// Non-H5 environments (mini programs)
			uni.getFileSystemManager().readFile({
				filePath: file.path, // Use file.path from the chosen file
				encoding: 'utf-8',
				success: (res) => resolve(res.data),
				fail: (err) => reject(err)
			});
			// #endif
		});
	};

	// 解析CSV数据
	const parseCSV = (csvText) => {
		const lines = csvText.split('\n');
		const headers = lines[0].split(',').map(h => h.trim());
		const result = [];

		for (let i = 1; i < lines.length; i++) {
			if (!lines[i].trim()) continue;

			const obj = {};
			const currentline = lines[i].split(',');

			for (let j = 0; j < headers.length; j++) {
				obj[headers[j]] = currentline[j] ? currentline[j].trim() : '';
			}

			// 确保有必要的字段
			if (obj['主订单编号'] && obj['选购商品'] && obj['商品id']) {
				result.push({
					serial: obj['商品'],
					title: obj['选购商品'],
					desc: obj['主订单编号'],
					img: '' // 图片可以为空
				});
			}
		}

		return result;
	};

	onMounted(() => {
		loadData();
	});
</script>

<style lang="scss" scoped>
	.page-container {
		padding: 20rpx;
		background-color: #f8fafc;
		min-height: 100vh;
		box-sizing: border-box;

		.page-title {
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		}
	}

	.row-box {
		margin-top: 20rpx;

		.col-item {
			margin-top: 20rpx;

			&:first-child {
				margin-top: 0;
			}
		}
	}


	.item-card {
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		border: 2px solid transparent;

		&:hover {
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
			transform: translateY(-2px);
		}

		&.editing {
			border-color: #4f46e5;
			box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2);
			background-color: #f8fafc;
		}
	}

	.item-content {
		display: flex;
		padding: 24rpx;
		align-items: flex-start;
		gap: 24rpx;
	}

	.image-container {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
		overflow: hidden;
		position: relative;
		flex-shrink: 0;
		background-color: #f1f5f9;
		cursor: pointer;
		border: 1px dashed #cbd5e1;
		transition: all 0.3s ease;

		&:hover {
			border-color: #4f46e5;
			background-color: #eef2ff;
		}
	}

	.item-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.upload-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #64748b;
		background-color: rgba(241, 245, 249, 0.7);
	}

	.upload-text {
		font-size: 24rpx;
		margin-top: 8rpx;
	}

	.content-container {
		flex: 1;
		min-height: 160rpx;
		/* 保持与图片相同高度 */
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.edit-fields {
		width: 100%;
	}

	.input-field {
		margin-bottom: 16rpx;
	}

	.input-label {
		display: block;
		font-size: 24rpx;
		color: #64748b;
		margin-bottom: 4rpx;
	}

	.edit-input {
		width: 100%;
		padding: 12rpx 16rpx;
		border: 2px solid #e2e8f0;
		border-radius: 6rpx;
		font-size: 28rpx;
		background-color: #fff;
		transition: all 0.2s;

		&:focus {
			border-color: #4f46e5;
			box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2);
			outline: none;
		}
	}

	.display-fields {
		.info-row {
			display: flex;
			margin-bottom: 16rpx;
			align-items: center;
		}

		.info-label {
			color: #64748b;
			font-size: 28rpx;
			width: 80rpx;
			flex-shrink: 0;
		}

		.info-value {
			color: #1e293b;
			font-size: 28rpx;
			font-weight: 500;
		}
	}

	.action-buttons {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
		min-width: 140rpx;
		margin-left: 16rpx;
	}

	.selection-checkbox {
		margin-bottom: 12rpx;
	}

	.action-btn {
		border: none;
		border-radius: 6rpx;
		padding: 0 20rpx;
		height: 56rpx;
		line-height: 56rpx;
		font-size: 26rpx;
		font-weight: 500;
		transition: all 0.2s;
		margin: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 6rpx;

		&:active {
			transform: scale(0.98);
		}

		&:disabled {
			opacity: 0.6;
			cursor: not-allowed;
		}
	}

	.edit-btn {
		background-color: #4f46e5;
		color: white;

		&:hover {
			background-color: #4338ca;
		}
	}

	.save-btn {
		background-color: #10b981;
		color: white;

		&:hover {
			background-color: #059669;
		}
	}

	.cancel-btn {
		background-color: #f59e0b;
		color: white;

		&:hover {
			background-color: #d97706;
		}
	}

	.delete-btn {
		background-color: #ef4444;
		color: white;

		&:hover {
			background-color: #dc2626;
		}
	}

	.opts {
		margin-top: 20rpx;
	}

	.add-actions {
		display: flex;
		gap: 20rpx;
		padding: 20rpx;
		justify-content: center;
	}

	.btn {
		border: none;
		border-radius: 8rpx;
		padding: 0 24rpx;
		height: 64rpx;
		line-height: 64rpx;
		font-size: 26rpx;
		font-weight: 500;
		transition: all 0.2s;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8rpx;

		&:active {
			transform: scale(0.98);
		}

		&:disabled {
			opacity: 0.6;
			cursor: not-allowed;
		}
	}

	.add-btn {
		background-color: #4f46e5;
		color: white;
		width: 100%;

		&:hover {
			background-color: #4338ca;
		}
	}

	.confirm-btn {
		background-color: #10b981;
		color: white;

		&:hover {
			background-color: #059669;
		}
	}

	.opts {
		display: flex;
		gap: 16rpx;
		flex-wrap: wrap;

		.btn {
			margin: 0;
		}
	}
</style>